# -*-coding:utf-8-*-
import re
import os
import tempfile
import random
import threading

# global props for properties in use
global props
props = {}
get_lock = threading.Lock()
put_lock = threading.Lock()


class Properties:
    def __init__(self, file_name):
        self.file_name = file_name
        self.properties = {}
        try:
            fopen = open(self.file_name, 'r')
            for line in fopen:
                line = line.strip()
                if line.find('=') > 0 and not line.startswith('#'):
                    strs = line.split('=', 1)
                    self.properties[strs[0].strip()] = strs[1].strip()
        except Exception, e:
            raise e
        else:
            fopen.close()

    def has_key(self, key):
        return key in self.properties

    def get(self, key, default_value=''):
        get_lock.acquire()
        if key in self.properties:
            get_lock.release()
            return self.properties[key]
        get_lock.release()
        return default_value

    # save in props file
    def put(self, key, value):
        put_lock.acquire()
        self.properties[key] = value
        replace_property(self.file_name, key + '=.*', key + '=' + value, True)
        put_lock.release()

    # do not save in props file
    def add(self, key, value):
        self.properties[key] = value

    def get_keys(self):
        return self.properties.keys()


def parse(file_name):
    return Properties(file_name)


def replace_property(file_name, from_regex, to_str, append_on_not_exists=True):
    tmpfile = tempfile.TemporaryFile()

    if os.path.exists(file_name):
        r_open = open(file_name, 'r')
        pattern = re.compile(r'' + from_regex)
        found = None
        for line in r_open:
            if pattern.search(line) and not line.strip().startswith('#'):
                found = True
                line = re.sub(from_regex, to_str, line)
            tmpfile.write(line)
        if not found and append_on_not_exists:
            tmpfile.write('\n' + to_str)
        r_open.close()
        tmpfile.seek(0)

        content = tmpfile.read()

        if os.path.exists(file_name):
            os.remove(file_name)

        w_open = open(file_name, 'w')
        w_open.write(content)
        w_open.close()

        tmpfile.close()
    else:
        print "file %s not found" % file_name


def get_props():
    global props
    return props


def agent_parser():
    global props
    agents = []
    keys = props.get_keys()
    for k in keys:
        if k.startswith('header.Agent'):
            agents.append(props.get(k))
    return agents


def header_parser(host):
    global props
    header_host = ''
    if host == 'book':
        header_host = props.get('header.bookHost')
    elif host == 'api':
        header_host = props.get('header.apiHost')
    header = {'Host': header_host,
              'Accept': props.get('header.Accept'),
              'Accept-Encoding': props.get('header.Accept-Encoding'),
              'Accept-Language': props.get('header.Accept-Language'),
              'Connection': props.get('header.Connection')}
    return header


def get_header(host='book'):
    header = header_parser(host)
    agents = agent_parser()
    header['User-Agent'] = random.choice(agents)
    return header


def props_init():
    global props
    file_path = 'props/doemax_py.properties'
    props = parse(file_path)


if __name__ == '__main__':
    props_init()
    print
